from flask import (
    Blueprint,
    render_template,
    request,
    session,
    redirect,
    url_for,
    g,
    jsonify
)
from .forms import (
    LoginForm, ResetPwdForm,
    BlockadeForm, UnblockForm,
    TradeForm, UpdateAccountForm
)
from .models import *
from apps.cms.decorators import login_need
import config
from exit import db
from apps.api.models import User, UserRecord
from flask_paginate import Pagination, get_page_parameter
from utils import restful, common_util, img_path, api_util, api_util_v2
from apps.common.models import *
from datetime import datetime, date
import os
import shortuuid
from sqlalchemy import or_, func
from decimal import Decimal
from .views_cms import bp
from apps.mall.models import *
from apps.mall.models_v2 import *
import requests
import json


@bp.route('/user_extend_manage/')
@login_need
def user_extend_manage():
    user_id = request.args.get('user_id')
    return render_template('cms_2/user_extend.html', user_id=user_id)


@bp.route('/user_extend_info/')     # 用户商品身份信息
def user_extend_info():
    user_id = request.args.get('user_id')
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    data_obj = Goods.query.filter_by(status=1)
    data_info = data_obj.order_by(Goods.priority).slice(start, end)
    total = data_obj.count()
    data_list = list()
    user = User.query.filter_by(id=user_id).first()
    for i in data_info:
        data_json = api_util_v2.search_create_user_extend(i.id, user_id, 0)
        data_json['username'] = user.username
        data_json['phone'] = user.phone
        data_json['goods_name'] = i.name
        data_list.append(data_json)
    return restful.table_success(data=data_list, count=total)


@bp.route('/update_user_extend/', methods=['POST'])     # 更新用户商品身份信息
@login_need
def update_user_extend():
    user_id = request.form.get('user_id_')
    goods_id = request.form.get('goods_id')
    user_status = request.form.get('user_status', type=int)
    goods = Goods.query.filter_by(id=goods_id).first()
    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')

    user_extend = UserExtend2.query.filter_by(user_id=user_id, goods_id=goods_id).first()
    if user_extend is None:
        create_extend = UserExtend2(user_id=user_id, user_status=user_status, goods_id=goods_id)
        db.session.add(create_extend)
        user_extend_str = api_util_v2.user_extend_status_str(0)
        user_extend_str2 = api_util_v2.user_extend_status_str(user_status)
        record = '用户<{}>身份<{}>修改为<{}>'.format(goods.name, user_extend_str, user_extend_str2)
    else:
        user_extend_str = api_util_v2.user_extend_status_str(user_extend.user_status)
        user_extend_str2 = api_util_v2.user_extend_status_str(user_status)
        record = '用户<{}>身份<{}>修改为<{}>'.format(goods.name, user_extend_str, user_extend_str2)
        user_extend.user_status = user_status

    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, user_id=user_id, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/user_transfer_v2/')
@login_need
def user_transfer_v2():
    goods = Goods.query.filter_by(status=1).all()
    return render_template('cms_2/user_transfer_v2.html', goods=goods)


@bp.route('/user_transfer_trade/', methods=['POST'])
@login_need
def user_transfer_trade():
    phone = request.form.get('user_phone')
    goods_id = request.form.get('goods_id')
    num = request.form.get('num')
    num = int(num)
    if num < 0:
        return restful.params_error(message='数量不能小于1')
    user = User.query.filter_by(phone=phone).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    goods = Goods.query.filter_by(id=goods_id).first()
    if goods is None:
        return restful.params_error(message='未找到商品')
    user_extend = UserExtend2.query.filter_by(user_id=user.id, goods_id=goods_id, user_status=2).first()
    if user_extend is None:
        return restful.params_error(message='该用户不是供应商')

    goods.stock_c += num

    mall_trade = MallTrade(
        buyer_id=user.id, buyer_status=2, deal_type=5, deal_num=num,
        deal_price=goods.low_price, deal_money=goods.low_price * num, goods_id=goods.id
    )
    db.session.add(mall_trade)
    db.session.flush()
    mall_batch = MallBatch(
        order_id=mall_trade.id, goods_id=goods_id, user_id=user.id,
        price=goods.low_price, deal_num=num, s_num=num, s_num_sell=num, s_num_take=0, s_num_release=0, status=0,
    )
    db.session.add(mall_batch)

    api_util.user_record(user_id=user.id, r_label=23, r_type=8, r_state=1, r_wallet=1, num=num, order_id=mall_trade.id, r_coin=goods.price)
    record = '系统配货：<{}> 数量：<{}>'.format(goods.name, num)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, user_id=user.id, ip=request.remote_addr)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()

